package com.star.carservice.client.fragment;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import com.star.carservice.R;
import com.star.carservice.client.activity.RegisterActivity;
import com.star.carservice.client.fragment.base.BaseFragment;
import com.star.carservice.client.utils.StringUtils;
import com.star.carservice.client.utils.ToastUtils;
import com.star.carservice.client.widget.MyProgressDialog;
import com.star.carserviceapi.domain.request.SendValidCodeRequest;
import com.star.carserviceapi.domain.result.SendValidCodeResult;

public class RegisterStep1Fragment extends BaseFragment {

	private final static String TAG = RegisterStep1Fragment.class
			.getSimpleName();

	MyProgressDialog mProgressDialog = null;

	@InjectView(R.id.input_mobile)
	EditText input_mobile;

	@Override
	public String getLogTag() {
		return TAG;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		mProgressDialog = new MyProgressDialog(getActivity(), false);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		if (CacheViewIsNull()) {
			mCacheView = inflater.inflate(R.layout.frag_register_step1,
					container, false);

			ButterKnife.inject(this, mCacheView);
		}

		removeCacheView();

		return mCacheView;
	}

	@OnClick(R.id.btn_refresh_code)
	public void getCode(View view) {

		if (StringUtils.isBlank(getMobile())) {
			return;
		}

		execAsyncTask(new SendValidCodeTask(), new SendValidCodeRequest(
				getMobile(), SendValidCodeRequest.ACTION_CREATE));
	}

	private String getMobile() {
		return input_mobile.getText().toString().trim();
	}

	private void gotoStep2() {
		getActivity().getSupportFragmentManager().beginTransaction()
				.replace(R.id.view_placeholder, new RegisterStep2Fragment())
				.addToBackStack(null)

				.commit();

		RegisterActivity parnet = (RegisterActivity) getActivity();
		parnet.setMobile(getMobile());

	}

	class SendValidCodeTask extends
			AsyncTask<SendValidCodeRequest, Void, SendValidCodeResult> {

		@Override
		protected void onPreExecute() {
			mProgressDialog.show();
		}

		@Override
		protected SendValidCodeResult doInBackground(
				SendValidCodeRequest... params) {
			return getApi().sendValidCodeRequest(params[0]);
		}

		@Override
		protected void onPostExecute(SendValidCodeResult result) {
			mProgressDialog.dismiss();

			if (result.successful()) {
				gotoStep2();
			} else {
				ToastUtils.show(getActivity(), result.getMessage());
			}
		}

	}
}
